package com.rjhch.hadoopTest;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.fs.FileSystem;
import org.apache.hadoop.hbase.HBaseConfiguration;
import org.apache.hadoop.hbase.client.Admin;
import org.apache.hadoop.hbase.client.Connection;
import org.apache.hadoop.hbase.client.ConnectionFactory;
import org.apache.hadoop.security.UserGroupInformation;

/**
 * 放置一些公共组件工具
 */
public class CommonTools {
    private static final Log log = LogFactory.getLog(CommonTools.class);

    public static FileSystem hdfs;
    public static Admin admin;

    /**
     * 登录hdfs，此处配置写死，一般不需要改变
     */
    private static void login() throws Exception {
        if (UserGroupInformation.isSecurityEnabled()) {
            String keytabFile;
            if (System.getProperty("os.name").startsWith("Windows")) {
                keytabFile = "D:\\keytab\\hadoop.keytab";
            } else {
                keytabFile = "/etc/security/keytab/hadoop.keytab";
            }
            log.info("keytabFile: " + keytabFile);
            UserGroupInformation.loginUserFromKeytab("hadoop/hadoop01@HADOOP.COM", keytabFile);
        }
    }

    /**
     * 初始化系统
     */
    public static Configuration init() throws Exception {
        return init(null);
    }

    /**
     * 初始化系统，可指定额外配置文件
     */
    public static Configuration init(String... resourceFileNames) throws Exception {
        login();

        Configuration config = HBaseConfiguration.create();
        config.addResource("custom-hbase-site.xml");
        if (resourceFileNames != null && resourceFileNames.length != 0) {
            for (String resourceFileName : resourceFileNames) {
                config.addResource(resourceFileName);
            }
        }

        hdfs = FileSystem.get(config);
        Connection con = ConnectionFactory.createConnection(config);
        admin = con.getAdmin();
        return config;
    }
}
